/*
顺序存储线性表实现 动态：不够存放可以加空间（搬家）
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LIST_INIT_SIZE 100
#define LIST_INCREMENT 10
#define ElementType int
#define Status int
#define OVERFLOW -1
#define OK 1
#define ERROR 0

typedef struct
{
    ElementType* elem;
    int length;
    int listsize;
}SequenceList;

Status InitList(SequenceList *L);
Status ListInsert(SequenceList *L, int index, ElementType e);
Status ListDelete(SequenceList *L, int index, ElementType *e);
void ListPrint(SequenceList *L);

int main()
{

    SequenceList L;
    int i;
    ElementType e;
    ElementType data[9] = {11,-22,33,-3,-88,21,77,0,-9};
    InitList(&L);
    for(i = 1; i <= 9; i++)
        ListInsert(&L, i, data[i-1]);
    printf("after indert L = : ");
    ListPrint(&L);
    ListDelete(&L, 1, &e);
    printf("after delete L = : ");
    ListPrint(&L);

    ListDelete(&L, 1, &e);
    printf("after delete L = : ");
    ListPrint(&L);

    return 0;
}

Status InitList(SequenceList *L)
{
    L->elem = (ElementType *)malloc(LIST_INIT_SIZE * sizeof(ElementType));
    if(!L->elem) return ERROR;
    L->length = 0;
    L->listsize = LIST_INIT_SIZE;
    return OK;
}

Status ListInsert(SequenceList *L, int index, ElementType e)
{
    if(index < 1 || index > L->length + 1)
        return ERROR;
    ElementType *newbase;
    if(L->length >= L->listsize)
    {
        newbase = (ElementType *)realloc(L->elem, (L->listsize + LIST_INCREMENT) * sizeof(ElementType));
        if(!newbase) return ERROR;
        L->elem = newbase;
        L->listsize += LIST_INCREMENT;
    }
    int j;
    for(j = L->length; j > index - 1; j--)
    {
        L->elem[j] = L->elem[j-1];
    }
    L->elem[index-1] = e;
    (L->length)++;
    return OK;
}

Status ListDelete(SequenceList *L, int index, ElementType *e)
{
    if(index < 1 || index > L->length)
        return ERROR;
    *e = L->elem[index-1];
    for(int j = index - 1; j <= L->length; j++)
    {
        L->elem[j] = L->elem[j+1];
    }
    (L->length)--;
    return OK;
}

void ListPrint(SequenceList *L)
{
    for(int i = 0; i < L->length; i++)
    {
        printf("%d ", L->elem[i]);
    }
    printf("\n");
}
